package com.example.crondemo.result;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.util.Date;

/**
 * @author yanbl
 * @version V1.8
 * @Description: restlt
 * @Date 2021/6/30 11:59
 */
@Data
@ApiModel(value = "全局统一返回结果")
public class Result<T> {

    @ApiModelProperty(value = "状态码")
    private int code; // 返回状态码 0:成功 other:失败

    @ApiModelProperty(value = "返回消息提示")
    private String message; // 返回错误信息

    @ApiModelProperty(value = "返回数据")
    private T stocks; // 返回数据

    @ApiModelProperty(value = "返回时间")
    private Date time;  // 返回时间

    public Result() {
    }

    public Result(ResultCodeEnum resultCodeEnum){
        this.code = resultCodeEnum.getCode();
        this.message = resultCodeEnum.getMessage();
        this.time = new Date();
    }

    /**
     * 如果返回成功
     * @param <T>
     * @return
     */
    public static <T> Result<T> ok(){
        return ok(null);
    }

    /**
     * 返回成功并且带参数
     * @param data
     * @param <T>
     * @return
     */
    public static <T> Result<T> ok(T data) {
        Result<T> result = new Result<>();
        result.setStocks(data);
        result.setMessage(ResultCodeEnum.SUCCESS.getMessage());
        result.setCode(ResultCodeEnum.SUCCESS.getCode());
        result.setTime(new Date());
        return result;
    }

    /**
     * 返回失败
     * @param data
     * @param <T>
     * @return
     */
    public static <T> Result<T> fail(T data){
        Result<T> result = new Result<>();
        result.setTime(new Date());
        result.setStocks(data);
        result.setMessage(ResultCodeEnum.FAIL.getMessage());
        result.setCode(ResultCodeEnum.FAIL.getCode());
        return result;
    }

    /**
     * 返回失败
     * @param <T>
     * @return
     */
    public static <T> Result<T> fail() {
        return fail(null);
    }
}
